package com.neusoft.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.quartz.InterruptableJob;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.UnableToInterruptJobException;
import org.w3c.dom.Document;

import com.neusoft.common.db.BaseDAO;
import com.neusoft.init.InitTaskService;
import com.neusoft.task.VideoInfoBean;


/**
 * 任务启动类,它实现了quartz的job接口
 * @author 郑兴龙 zheng-xl@neusoft.com
 */

public class TimeToCaptureJob extends BaseDAO implements InterruptableJob{
	public static Logger logger = Logger.getLogger("" + TimeToCaptureJob.class + "");
	private URL appPath = Thread.currentThread().getContextClassLoader().getResource("");
	private String propertyFile = "videoSuperintendConfig.properties";
	private String HTTP_HEADER = "http://";
	private String HTTPS_HEADER = "https://";
	private String COLON = ":"; 

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		logger.info("定时轮询抓拍........开始...............");
		
		// 查询所定时轮训的项目
		JobDataMap data = arg0.getJobDetail().getJobDataMap();
		
		Configuration conf = InitTaskService.getProperties(appPath.getPath()+propertyFile);
		String taskId = data.get(InitTaskService.JOB_DATA_STRING_TASK_ID).toString();
		Map<String, String> session = getVideoConfig(conf);
		Map<String,String> map = new HashMap<String, String>();
    	map.put("loginName", session.get("loginName"));
    	map.put("loginPassword", session.get("loginPassword"));
    	map.put("loginIp", session.get("loginIp"));
    	map.put("loginPort", session.get("loginPort"));
    	map.put("sruServerIP", session.get("sruServerIP"));
    	map.put("sruServerPort", session.get("sruServerPort"));
    	map.put("sruServer", session.get("sruServer"));
		map.put("smuServer", session.get("smuServer"));
		map.put("scuServer", session.get("scuServer"));
		Map<String, String> loginMap = HttpClientSendRequest.sendInitLoginData(map);
		String nvsUrl =  session.get("smuServer");//smuServer
		loginMap.put("projectName", "");
		loginMap.put("nvsUrl", nvsUrl);
		String xmlData = MsgTemplateXML.getCommonXML(loginMap);
		loginMap.put("xmlData", xmlData);
		String cameraXML = getCameraList(loginMap);
		//xml解析 <CAMERA_CODE>042454216720101</CAMERA_CODE> 得到camera_code
		int _t=0;
		try {
		StringBuilder sXML = new StringBuilder();
		sXML.append(cameraXML);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		InputStream is = new ByteArrayInputStream(sXML.toString().getBytes("utf-8"));
		Document doc = dbf.newDocumentBuilder().parse(is);
		_t = doc.getElementsByTagName("CAMERA_NAME").getLength();
		List<VideoInfoBean> cameraList = new ArrayList<VideoInfoBean>();
		VideoInfoBean videoInfo = null;
		for(int i=0;i<_t;i++){
			videoInfo = new VideoInfoBean();
			videoInfo.setCameraCode(doc.getElementsByTagName("CAMERA_CODE").item(i).getTextContent());
			videoInfo.setCameraName(doc.getElementsByTagName("CAMERA_NAME").item(i).getTextContent());
			videoInfo.setIsOnline(doc.getElementsByTagName("IS_ONLINE").item(i).getTextContent());
			videoInfo.setCameraType(doc.getElementsByTagName("CAMERA_TYPE").item(i).getTextContent());
			videoInfo.setExtendStatus(doc.getElementsByTagName("EXTEND_STATUS").item(i).getTextContent());
			videoInfo.setCameraLocation(doc.getElementsByTagName("CAMERA_LOCATION").item(i).getTextContent());
			videoInfo.setVoiceInEnable(doc.getElementsByTagName("VOICE_IN_ENABLE").item(i).getTextContent());
			videoInfo.setChannelEnable(doc.getElementsByTagName("CHANNEL_ENABLE").item(i).getTextContent());
			videoInfo.setIsShared(doc.getElementsByTagName("IS_SHARED").item(i).getTextContent());
			videoInfo.setIsOutScc(doc.getElementsByTagName("IS_OUT_SCC").item(i).getTextContent());
			videoInfo.setOrgCode(doc.getElementsByTagName("ORG_CODE").item(i).getTextContent());
			videoInfo.setOrgName(doc.getElementsByTagName("ORG_NAME").item(i).getTextContent());
			videoInfo.setDevVendorType(doc.getElementsByTagName("DEV_VENDOR_TYPE").item(i).getTextContent());
			videoInfo.setDevFormType(doc.getElementsByTagName("DEV_FORM_TYPE").item(i).getTextContent());
			videoInfo.setDevName(doc.getElementsByTagName("DEV_NAME").item(i).getTextContent());
			videoInfo.setDevModelType(doc.getElementsByTagName("DEV_MODEL_TYPE").item(i).getTextContent());
			cameraList.add(videoInfo);
		}
		for(VideoInfoBean bean:cameraList){
			timeToCapture(loginMap,bean);
		}
		
		
		} catch (Exception e) {
			logger.error("获得摄像头XML数据时异常！");
			e.getStackTrace();
		}
		
		logger.info("定时轮询抓拍........结束...............");
		logger.info("进入下次job等待");
		
	}
	/**
	 * 获得摄像头列表
	 * @param map
	 * @return
	 */
	private String getCameraList(Map<String, String> map){
		String requestMsg = "";
		try {
			// 创建多线程的客户端
			MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
			HttpClient client = new HttpClient(connectionManager);

			PostMethod method = new UTF8PostMethod(map.get("nvsUrl"));

			// 执行http下发请求
			HttpClientSendRequest.getMethodResult(map.get("xmlData"), map.get("nvsUrl"), client, method);
			requestMsg = method.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return requestMsg;
}
	
	/**
	 * 获得视频配置信息
	 * @param conf
	 * @return
	 */
	private Map<String, String> getVideoConfig(Configuration conf) {
		//以下读取properties文件的值 
		String IP = conf.getValue("IP")+COLON;
        String user = conf.getValue("USER"); 
        String password = conf.getValue("PASSWORD");
        String scuServer = HTTP_HEADER + IP + conf.getValue("SCU_SMU_PORT") + "/SCU/SCU.do";
        String smuServer = HTTP_HEADER + IP + conf.getValue("SCU_SMU_PORT") + "/SMU/SMU.do";
        String sruServer = HTTPS_HEADER + IP + conf.getValue("SRU_PORT") + "/SRU/SRU.do";
        Map<String, String> session = new HashMap<String, String>();
        String loginIp = conf.getValue("LocalhostIP");
        String loginPort = conf.getValue("LocalhostPort");
        
        String portalLogin = HTTPS_HEADER + IP + conf.getValue("LOGIN_PORT") + "/login/beforeLogin?THPAccess=1&amp;loginname="+user+"&amp;loginpassword="+password;
	    session.put("portalLoginLink", portalLogin);
        session.put("portal_ip", conf.getValue("IP"));
        session.put("portal_port", conf.getValue("SRU_PORT"));
        session.put("portal_user", user);
        session.put("portal_password", password);
        session.put("scuServer", scuServer);
        session.put("smuServer", smuServer);
        
        session.put("loginName", user);
        session.put("loginPassword", password);
        session.put("loginIp", loginIp);
        session.put("loginPort", loginPort);
        session.put("sruServerIP", conf.getValue("IP"));
        session.put("sruServerPort", conf.getValue("SRU_PORT"));
        session.put("sruServer", sruServer);
		
        return session;
	}
	
	private static void timeToCapture(Map<String,String> loginMap,VideoInfoBean bean) {
		Map<String,String> map =  new HashMap<String,String>();
		 map.put("loginId", loginMap.get("loginId"));
		 map.put("CAMERA_CODE", bean.getCameraCode());
		 String xmlData = MsgTemplateXML.timeToCaptureXLM(map);
		 //接口回调消息
		 String requestMsg = "";
		 String nvsUrl = loginMap.get("scuServer");//scuServer
		 // 创建多线程的客户端
		 MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		 HttpClient client = new HttpClient(connectionManager);
		 PostMethod method = new UTF8PostMethod(nvsUrl);
		 HttpClientSendRequest.getMethodResult(xmlData, nvsUrl, client, method);
		 try {
			requestMsg = method.getResponseBodyAsString();
		} catch (IOException e) {
			logger.error("通过华为抓拍图片接口获得xml异常");
			e.printStackTrace();
		}
		logger.info("requestMsg:=="+requestMsg);
		    
	}
	

	public void interrupt() throws UnableToInterruptJobException {
		// TODO Auto-generated method stub
		
	}

}
